﻿using System.Net.Http;
using System.ServiceModel.Channels;
using System.Text.RegularExpressions;
using System.Web;

namespace YueRu.Common
{
    public sealed class IpHelper
    {
        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public static string GetClientIp(HttpRequestMessage requestMessage)
        {
            if (requestMessage.Properties.ContainsKey("MS_HttpContext"))
            {
                var request = (HttpContextWrapper)requestMessage.Properties["MS_HttpContext"];
                return request.Request.UserHostAddress;
            }
            if (requestMessage.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                var prop = (RemoteEndpointMessageProperty)requestMessage.Properties[RemoteEndpointMessageProperty.Name];
                return prop.Address;
            }
            return "ErrorIp";
        }

        /// <summary>
        /// 判断是否是Ip地址   
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string ip)
        {
            if (string.IsNullOrEmpty(ip) || ip.Length < 7 || ip.Length > 15) return false;
            const string regformat = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(ip);
        }
    }
}